import { BufferAsset, Component, EditBox, EventTouch, Node, NodeEventType, _decorator, resources, view } from 'cc';
import { Game } from '../game/Game';
import { Xlsx } from '../game/cfg/Xlsx';
import { KProto } from '../game/proto/KProto';
import KProtoStruct from '../game/proto/KProtoStruct';
import { Conn } from './conn/Conn';
const { ccclass, property } = _decorator;

/**
 * 主入口
 */
@ccclass('Main')
export class Main extends Component {

    static ins: Main;

    @property(Node)
    gameUI: Node;
    @property(Node)
    menuUI: Node;
    @property(EditBox)
    inputUrl: EditBox;
    @property(EditBox)
    inputName: EditBox;

    localGame: Game;
    loaded = false;
    conning = false;

    protected onLoad(): void {
        Main.ins = this;
        (window as any)["Main"] = this;
        this.node.on(NodeEventType.SIZE_CHANGED, () => {
            Conn.send(KProtoId.updateScreen, { screen: view.getVisibleSize() });
        });
    }

    protected start(): void {
        Xlsx.init(kcoder);
        KProto.init(kcoder);
        KProto.loadAll(KProtoStruct);
        resources.load("data", BufferAsset, (err, data) => {
            Xlsx.load(new Uint8Array(data.buffer()));
            this.loaded = true;
        });

        this.gameUI.active = false;
        this.menuUI.active = true;

        this.inputUrl.string = location.hostname + ":888";
    }

    onClickStart(e: EventTouch, data: any) {
        this.startGame(data)
    }

    startGame(type: string) {
        if (!this.loaded) {
            return;
        }

        if (type === "local") {
            this.localGame?.scene.stop();
            this.localGame = new Game().start();
            Conn.connLocal(this.localGame, () => {
                this.sendJoin();
            });
        } else if (type === "remote") {
            if (this.conning) return;
            this.conning = true;
            Conn.connRemote(`ws://${this.inputUrl.textLabel.string}`, () => {
                this.conning = false;
                this.sendJoin();
            }, () => {
                this.conning = false;
            }, () => {
                this.conning = false;
            });
        }
    }

    sendJoin() {
        Conn.send(KProtoId.joinGame, { name: this.inputName.textLabel.string, screen: view.getVisibleSize() });
    }

}